package com.heiyu.controller;

import com.alibaba.fastjson.JSON;
import com.heiyu.controller.request.LoginRequest;
import com.heiyu.controller.response.BaseResponse;
import com.heiyu.dao.AdminUserInfoMapper;
import com.heiyu.entity.AdminUserInfo;
import com.heiyu.utils.CacheKey;
import com.heiyu.utils.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api
@RestController
public class LoginController extends AdminBaseController {

    @Autowired
    private AdminUserInfoMapper adminUserInfoMapper;

    @ApiOperation(value = "login", notes = "登录")
    @PostMapping("login")
    public Object login(@ModelAttribute LoginRequest request) {
        BaseResponse response = new BaseResponse();
        if (StringUtils.isBlank(request.getUserName()) || StringUtils.isBlank(request.getPassword())) {
            response.error("参数错误");
        }else{
            AdminUserInfo userInfo= new AdminUserInfo();
            userInfo.setUserName(request.getUserName());
            List<AdminUserInfo> list = this.adminUserInfoMapper.selectList(userInfo);
            if(CollectionUtils.isEmpty(list)){
                response.error("用户不存在");
            }else{
                if(list.get(0).getPassword().equals(Md5Utils.md5(request.getPassword()))){
                    String token = System.currentTimeMillis()+RandomStringUtils.random(6);
                    redisUtils.set(CacheKey.ADMIN_TOKEN+token, JSON.toJSONString(list.get(0)));
                    setHeader("Authorization",token);
                    response.success();
                }else{
                    response.error("账号或密码错误");
                }
            }
        }
        return response;
    }


}
